﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace TCPServer_02
{
    class Program
    {
        private static TcpClient client;

        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Loopback,2300));
            listener.Start();
            Console.WriteLine("服务端在{0}进行监听...",new IPEndPoint (IPAddress. Loopback, 2300));
            TcpClient client = listener.AcceptTcpClient() ;
            NetworkStream ns = client.GetStream();
            BinaryReader br = new BinaryReader(ns);
            BinaryWriter bw = new BinaryWriter(ns);

            string str;
            var t1 = Task.Run(() => {
                while (true) {
                    try
                    {
                        Console.WriteLine("服务器收到的消息：" + br.ReadString());
                    }
                    catch (Exception e){
                        Console.WriteLine(e.Message);
                        Console.ReadKey();
                        break;
                    }
                }
            });

            var t2 = Task.Run(() => {
                while (true)
                {
                    try
                    {
                        str = Console.ReadLine();
                        Console.WriteLine("服务器收到的消息：" + str);
                        bw.Write(str);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        Console.ReadKey();
                        break;
                    }
                }
            });

            t1.Wait();
            t2.Wait();
        }
    }
}
